package com.unziper.helpapp.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnZiper implements IUnZiper {

	/*public static void main(String[] args) {
		UnZiper unZiper = new UnZiper();
		File inFile = new File("C:\\Users\\BoRko\\Desktop\\com.zip");
		unZiper.unzip(inFile);
	}*/

	public static final String OUTPUT_FOLDER = "C:\\UnzipedContent";

	private File inFile;
	private File outFile;
	private boolean isUnziped;

	public UnZiper() {
		initialize();
	}

	public UnZiper(File inFile) {
		setInFile(inFile);
		initialize();
	}

	public void unzip(File inFile) {
		setInFile(inFile);
		byte[] buffer = new byte[1024];

		// Create output directory if don't exist.
		if (!getOutFile().exists()) {
			getOutFile().mkdir();
		}

		try {
			ZipInputStream inputStream = new ZipInputStream(new FileInputStream(getInFile()));
			ZipEntry zipEntry = inputStream.getNextEntry();

			while (zipEntry != null) {
				String currentFileName = zipEntry.getName();
				File currentFile = new File(getOutFile() + File.separator + currentFileName);
				if (!currentFile.getName().contains(".")) {
					currentFile.mkdirs();
				} else {
					currentFile.createNewFile();
					FileOutputStream outputStream = new FileOutputStream(currentFile);

					int lenght = 0;
					while ((lenght = inputStream.read(buffer)) > 0) {
						outputStream.write(buffer, 0, lenght);
					}
					outputStream.close();
				}
				zipEntry = inputStream.getNextEntry();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		setUnziped(true);
	}

	private void initialize() {
		setOutFile(new File(OUTPUT_FOLDER));
	}

	public File getInFile() {
		return inFile;
	}

	public void setInFile(File inFile) {
		this.inFile = inFile;
	}

	public File getOutFile() {
		return outFile;
	}

	public void setOutFile(File outFile) {
		this.outFile = outFile;
	}

	public boolean isUnziped() {
		return isUnziped;
	}

	public void setUnziped(boolean isUnziped) {
		this.isUnziped = isUnziped;
	}

}
